# -*- coding: utf-8 -*-
'''
Created on Jun 27, 2014

@author: GIANG NGUYEN
'''
import os
import sys
from urlparse import urljoin
import workerpool
# sys.path.append('C:/longhoanggiang/pyLib')
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import lib
import logging
import sqlite3
import json

logging.basicConfig(level=logging.DEBUG, format='%(levelname)s :: %(asctime)s :: %(message)s', datefmt='%d/%m/%Y %H:%M:%S')

crawlResult = {}

class CrawlJob(workerpool.Job):
    
    def __init__(self, callback, *args):
        self.callback = callback
        self.args = args
        
    def run(self):
        detail, key = self.callback(*self.args)
        global crawlResult
        crawlResult[key] = detail

class Crawler():
    
    def getChapters(self, url):
        data = []
        _url = url
        fakeChapter = raw_input("Use original chapter name (y/n): ")
        fakeChapter = True if fakeChapter == 'y' or fakeChapter == 'Y' else False
        tree = lib.Web.load(_url).build_tree()
        nodeItems = tree.xpath("//h3[contains(., 'Đọc từ đầu')]/following-sibling::ul[1]/li/a".decode('utf-8'))
        chapterCount = 1
        for node in nodeItems:
            link = node.get('href')
            if link != '':
                link = urljoin(url, link)
            if link == '': continue
            if fakeChapter:
                name = lib.stringify(node)
                name = name.replace(' : ', ': ')
            else:
                name = "CHƯƠNG {0}".format(chapterCount)
            data.append({'name': name, 'url': link, 'filename': lib.md5(link), 'parent': 0})
            chapterCount += 1
        return data
    
    def getDetail(self, url):
        try:
            tree = lib.Web.load(url).build_tree()
            for xpathStr in ["//div[contains(@class, 'entry')]//div[@class='ratingblock ']/..", "//div[@id='content']//div[@class='entry']"]:
                print xpathStr
                nodeContent = tree.xpath(xpathStr)
                if len(nodeContent) == 0 : continue
                nodeContent = nodeContent[0]
                lib.Etree.cleanNode("./div[@class='ann']/following-sibling::a[1]", nodeContent)
                lib.Etree.cleanNodeNextSibling(nodeContent.xpath("./div[@style='display: none']"), True)
                lib.Etree.cleanNodeNextSibling(nodeContent.xpath("./div[@class='chuyen-chuong']"), True)
                lib.Etree.cleanNode("./div[@class='ann']", nodeContent)
                
                def handelImgTag(node):
#                     if node.tag == 'img':
#                         imgUrl = node.get('src')
#                         if imgUrl != '':
#                             imgUrl = urljoin(url, imgUrl)
#                             return "<img src=\"{0}\" width=\"100%\" />".format(imgUrl)
                    return None
                content = lib.getText(nodeContent, paragraph_break=2, breakline_html=False, callback=handelImgTag).strip()
                content = content.replace("\n\n\n\n", "<br /><br />")
                content = content.replace("\n", "<br />")
                if type(content).__name__ == 'unicode':
                    content = content.encode('utf-8')
                return content, lib.md5(url)
        except:
            logging.error("Error {0} with URL: {1}".format(sys.exc_info()[1], url))
            raise
        
        
    
    def createTable(self, connection):
        cursor = connection.cursor()
        cursor.execute("CREATE TABLE IF NOT EXISTS udv_content('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'hash' VARCHAR(32), 'name' VARCHAR(200), 'content' BLOB, 'is_header' INTEGER DEFAULT 0)")
        cursor.execute("CREATE INDEX IF NOT EXISTS hash_index ON udv_content(hash)")
        cursor.execute("CREATE INDEX IF NOT EXISTS id_index ON udv_content(id)")
        cursor.close()
    
    def getStory(self, url, output=None):
        if output == None:
            output = lib.extractText(r"http://truyenngontinh.com/truyen/([^/]+)", url, 1)
        path = "/longhoanggiang/database/{0}".format(output)
        if os.path.exists(path):
            os.unlink(path)
        if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path), 0777)
        connection = sqlite3.connect(path)
        self.createTable(connection)
        
        chapters = self.getChapters(url)
        pool = workerpool.WorkerPool(size=10)
        
        for chapter in chapters:
            pool.put(CrawlJob(self.getDetail, chapter['url']))
        pool.shutdown()
        pool.wait()
        
        for chapter in chapters:
            name = chapter['name']
            detail = crawlResult[lib.md5(chapter['url'])]
            detail = "<h4 id='title'>{0}</h4>{1}".format(name, detail)
            cursor = connection.cursor()
            cursor.execute("INSERT INTO udv_content('name', 'content') VALUES(?, ?)", [name.decode('utf-8'), buffer(lib.compressStr(json.dumps(detail)))])
            cursor.close()
            print name
            print detail[0:200]
        
        connection.commit()
        connection.close()
        logging.info("saved database in {0}".format(path))
    
    def getMutipleStory(self, urls, output=None):
        if output == None or output == '':
            output = raw_input("Enter database name: ")
        path = "/longhoanggiang/database/{0}".format(output)
        if os.path.exists(path):
            os.unlink(path)
        if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path), 0777)
        connection = sqlite3.connect(path)
        self.createTable(connection)
        for url in urls:
            chapters = self.getChapters(url)
            pool = workerpool.WorkerPool(size=10)
            for chapter in chapters:
                pool.put(CrawlJob(self.getDetail, chapter['url']))
            pool.shutdown()
            pool.wait()
            for chapter in chapters:
                name = chapter['name']
#                 detail = self.getDetail(chapter['url'])
                detail = crawlResult[lib.md5(chapter['url'])]
                detail = "<h4 id='title'>{0}</h4>{1}".format(name, detail)
                cursor = connection.cursor()
                cursor.execute("INSERT INTO udv_content('name', 'content') VALUES(?, ?)", [name.decode('utf-8'), buffer(lib.compressStr(json.dumps(detail)))])
                cursor.close()
                print name
                print detail
        
        connection.commit()
        connection.close()
        
    
if __name__ == '__main__':
    
    c = Crawler()
    url = raw_input("Enter url: ")
    if url.startswith("http:"):
        if url.find('|') > -1:
            urls = url.split('|')
            c.getMutipleStory(urls)
        else:
            c.getStory(url)
    else:
        logging.error("Inivalid URL")
    logging.info("Finished crawl")
    os._exit(1)
    